package c15;

/**
 * MyLatch是一个协同的工具类，主要用来演示countDownLatch的原理，可以模拟等待多个线程都完成了的场景，
 * 比如说多个子任务计算，再将计算结果汇总
 * 或者是旅游团出去旅游，需要等团员都到齐才能开始活动
 */
public class MyLatch {
    int count;

    public MyLatch(int num) {
        this.count = num;
    }

    public synchronized void await() {
        while (count > 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void countDown() {
        count--;
        if (count <= 0) {
            notifyAll();
        }
    }

    static class Worker extends Thread {
        private MyLatch latch;

        public Worker(MyLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " working...");
            try {
                Thread.sleep((int) Math.random() * 100);
                this.latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int num = 10;
        MyLatch latch = new MyLatch(num);
        for (int i = 0; i < num; i++) {
            Worker worker = new Worker(latch);
            worker.start();
        }
        latch.await();
        System.out.println("main thread end");
    }
}
